#include "StdAfx.h"
#include "Saver.h"

Saver g_saver;
Saver * gsaver = &g_saver;

Saver::Saver(void)
{
	mdir = TEXT("");
	mhead = TEXT("");
	mext = TEXT(".dat");

	mcnt = 0;
	mtimelast = TEXT("");
}
Saver::~Saver(void)
{
	mfile.Close();
}

void Saver::test()
{
// gen simulate data;
	ushort buf[1024];
	int len = 1024;

	for (int i = 0; i < len; i++ )
	{
		buf[i] = i;
	}
// test flow;
	start();
	saveStrWd( buf, len );
	saveStrWd( buf, len );
	stop();

}

int Saver::start()
{
	mcnt = 0;
	mtimelast = TEXT("");

	return 1;
}
void Saver::stop()
{
	mfile.Close();
}

int Saver::saveStrWd( ushort * buf, int len )
{
// once a file;
	int err = 0;

	if( ( len < 0 ) || ( buf == NULL ) )
		return ++err;

// open file;
	genFileName();
	if( mfile.Open( mfn, 3 ) )		return ++err; // txt; create;

// save data;
	CString s;
	for ( int i = 0; i < len; i++ )
	{
		s.Format(TEXT("%d"), buf[i]);
		mfile.writeLine( s );
	}
	mfile.Close();

	return err;
}

void Saver::genFileName()
{
	CString s = getDataTime();
	if ( s == mtimelast )
	{
		s.Format(TEXT("%s-%d"), mtimelast, ++mcnt);
		//s = mtimelast + s;
	}
	else
	{
		mtimelast = s;
		mcnt = 0;
	}
	mfn = mdir + mhead + TEXT("-") + s + mext;

}
CString Saver::getDataTime()
{
	CTime ct = CTime::GetCurrentTime();

	// xx-"20131105-222825"-x.dat;
	CString cs;
	cs.Format(TEXT("%04d%02d%02d-%02d%02d%02d"),
		ct.GetYear(), ct.GetMonth(), ct.GetDay(),
		ct.GetHour(),ct.GetMinute(),ct.GetSecond());

	return cs;
}